<?php
/**
 * Created by PhpStorm.
 * User: mofeng
 * Date: 08/08/2018
 * Time: 1:04 PM
 */

namespace App\Traits;


trait RecordsActivity
{

	public static function bootRecordsActivity()
	{
		if (auth()->guest()) return;//只有登录用户才会记录动作

		foreach (static::getActivitiesToRecord() as $event) {
			static::created(function ($thread) use ($event) {
				$thread->recordActivity($event);
			});
		}

		static::deleting(function ($model) {
			$model->activity()->delete();
		});
	}

	/**
	 * 写记录的监听动作数组
	 * @return array
	 */
	protected static function getActivitiesToRecord()
	{
		return ['created'];
	}

	/**
	 * @param $event
	 * @throws \ReflectionException
	 */
	protected function recordActivity($event)
	{
		$this->activity()->create([
			'user_id' => auth()->id(),
			'type'    => $this->getActivityType($event),
		]);
	}

	protected function activity()
	{
		return $this->morphMany('App\Activity', 'subject');
	}

	/**
	 * @param $event
	 * @return string
	 * @throws \ReflectionException
	 */
	protected function getActivityType($event): string
	{
		return $event . "_" . strtolower((new \ReflectionClass($this))->getShortName());
	}
}